import { watch, ref, onMounted, onBeforeUnmount, isRef } from "vue";

export default function useElementInfo(eleRef) {
  const data = ref({ width: 0, height: 0 });

  if (isRef(eleRef)) {
    watch(
      eleRef,
      (v) => {
        if (v) {
          const res = handleCalcElementInfo(v);
          if (res) {
            data.value.width = res.width;
            data.value.height = res.height;
          }
        }
      },
      {
        immediate: true,
      }
    );
  }

  function handler() {
    const v = isRef(eleRef) ? eleRef.value : document.querySelector(eleRef);

    const res = handleCalcElementInfo(v);
    if (res) {
      data.value.width = res.width;
      data.value.height = res.height;
    }
  }
  onMounted(() => {
    handler();
    window.addEventListener("resize", handler);
  });
  onBeforeUnmount(() => {
    window.removeEventListener("resize", handler);
  });

  return data;
}

function handleCalcElementInfo(el) {
  if (!el) return null;
  return el.getBoundingClientRect();
}
